<script setup>
import { ref } from 'vue'
import PageContainer from '@/components/PageContainer.vue'
import { useUserStore } from '@/stores'
import { userUpdateInfoService } from '@/api/user'
// 引入储存中的个人信息
const {
  user: { username, nickname, email, id },
  getUserInfo
} = useUserStore()
// 表单数据
const userInfo = ref({ username, nickname, email, id })

const formRef = ref()
// 表单校验规则
const rules = ref({
  nickname: [
    { required: true, message: '请输入用户昵称', trigger: 'blur' },
    {
      pattern: /^\S{2,10}$/,
      message: '昵称必须是2-10位的非空字符',
      trigger: 'blur'
    }
  ],
  email: [
    { required: true, message: '请输入邮箱地址', trigger: 'blur' },
    { type: 'email', message: '请输入正确的邮箱地址', trigger: 'blur' }
  ]
})

// 提交表单
const onSubmit = async () => {
  const valid = await formRef.value.validate()
  if (valid) {
    await userUpdateInfoService(userInfo.value)
    await getUserInfo()
    ElMessage.success('修改成功')
  }
}
</script>

<template>
  <PageContainer title="基本资料">
    <el-form :model="userInfo" :rules="rules" ref="formRef" label-width="100px">
      <el-form-item label="登录名称">
        <el-input v-model="userInfo.username" disabled></el-input>
      </el-form-item>
      <el-form-item label="用户昵称" prop="nickname">
        <el-input v-model="userInfo.nickname"></el-input>
      </el-form-item>
      <el-form-item label="用户邮箱" prop="email">
        <el-input v-model="userInfo.email"></el-input>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="onSubmit">提交修改</el-button>
      </el-form-item>
    </el-form>
  </PageContainer>
</template>
